#Boa:Frame:FrameSO
#coding=utf-8

import wx
import wx.grid
import wx.calendar

from PopupTWinCustomer import *
import DlgCustomerChoice
import DlgSelectPro
import DlgPayment,DlgEditPro

import dbmngr

from product import *
from config import *
from DlgProGX import *

from singleton import *


import  wx.lib.printout as  printout
from MyPrinter import *

import kit

def create(parent):
    return FrameSO(parent)

[wxID_FRAMESO, wxID_FRAMESOBTNADDPRO, wxID_FRAMESOBTNCANCEL, 
 wxID_FRAMESOBTNHISTORY, wxID_FRAMESOBTNNEWPRO, wxID_FRAMESOBTNPAYMENT, 
 wxID_FRAMESOBTNPRINT, wxID_FRAMESOBTNSAVE, wxID_FRAMESOBTNSHOWCUSTOMER, 
 wxID_FRAMESOCOMBOBOX_DELIVERY, wxID_FRAMESOCOMBOBOX_STAFF, 
 wxID_FRAMESODATESO, wxID_FRAMESOGRIDSOPROLIST, wxID_FRAMESOSTATICBOX1, 
 wxID_FRAMESOSTATICBOX_HISTORY, wxID_FRAMESOSTATICTEXT1, 
 wxID_FRAMESOSTATICTEXT2, wxID_FRAMESOSTATICTEXT3, wxID_FRAMESOSTATICTEXT4, 
 wxID_FRAMESOSTATICTEXT_CUST, wxID_FRAMESOSTATICTEXT_DATE, 
 wxID_FRAMESOSTATICTEXT_DELIVERY, wxID_FRAMESOSTATICTEXT_MEMO, 
 wxID_FRAMESOSTATICTEXT_SHISHOU, wxID_FRAMESOSTATICTEXT_SOID, 
 wxID_FRAMESOSTATICTEXT_STAFF, wxID_FRAMESOSTATICTEXT_YINGSHOU, 
 wxID_FRAMESOSTATICTEXT_YOUHUI, wxID_FRAMESOTCCUSTOMER, wxID_FRAMESOTCMEMO, 
 wxID_FRAMESOTCPAID, wxID_FRAMESOTCSHISHOU, wxID_FRAMESOTCTOTAL, 
 wxID_FRAMESOTCUNPAID, wxID_FRAMESOTCYINGSHOU, wxID_FRAMESOTCYOUHUI, 
 wxID_FRAMESOTSOID, 
] = [wx.NewId() for _init_ctrls in range(37)]

class FrameSO(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAMESO, name=u'FrameSO', parent=prnt,
              pos=wx.Point(-8, 117), size=wx.Size(1288, 652),
              style=wx.THICK_FRAME | wx.DEFAULT_FRAME_STYLE,
              title=u'\u9500\u552e\u8ba2\u5355')
        self.SetClientSize(wx.Size(1280, 618))
        self.Center(wx.BOTH)
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundStyle(wx.BG_STYLE_COLOUR)
        self.SetBackgroundColour(wx.Colour(183, 209, 173))
        self.Bind(wx.EVT_CLOSE, self.OnFrameSOClose)

        self.staticText_SOID = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_SOID,
              label=u'\u5355\u53f7\uff1a', name=u'staticText_SOID', parent=self,
              pos=wx.Point(408, 48), size=wx.Size(64, 14), style=0)
        self.staticText_SOID.SetForegroundColour(wx.Colour(255, 0, 0))

        self.staticText_date = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_DATE,
              label=u'\u65e5\u671f\uff1a', name=u'staticText_date', parent=self,
              pos=wx.Point(408, 96), size=wx.Size(56, 14), style=0)

        self.dateSO = wx.DatePickerCtrl(id=wxID_FRAMESODATESO, name=u'dateSO',
              parent=self, pos=wx.Point(472, 88), size=wx.Size(136, 22),
              style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
        self.dateSO.SetLabel(u'2013-11-27')
        self.dateSO.SetValue(wx.DateTimeFromDMY(27, 10, 2013, 0, 0, 0))
        self.dateSO.SetWindowVariant(wx.WINDOW_VARIANT_NORMAL)
        self.dateSO.Bind(wx.EVT_DATE_CHANGED, self.OnDateSODateChanged,
              id=wxID_FRAMESODATESO)

        self.staticText_cust = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_CUST,
              label=u'\u5ba2\u6237\uff1a', name=u'staticText_cust', parent=self,
              pos=wx.Point(72, 88), size=wx.Size(64, 14), style=0)

        self.staticText_delivery = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_DELIVERY,
              label=u'\u9001\u8d27\uff1a', name=u'staticText_delivery',
              parent=self, pos=wx.Point(68, 136), size=wx.Size(68, 14),
              style=0)

        self.comboBox_delivery = wx.ComboBox(choices=[],
              id=wxID_FRAMESOCOMBOBOX_DELIVERY, name=u'comboBox_delivery',
              parent=self, pos=wx.Point(136, 136), size=wx.Size(472, 24),
              style=0, value=u'')
        self.comboBox_delivery.SetHelpText(u'')
        self.comboBox_delivery.SetLabel(u'')
        self.comboBox_delivery.SetStringSelection(u'')
        self.comboBox_delivery.SetToolTipString(u'配送地址')

        self.staticText_YingShou = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_YINGSHOU,
              label=u'\u5e94\u6536\u91d1\u989d\uff1a',
              name=u'staticText_YingShou', parent=self, pos=wx.Point(72, 440),
              size=wx.Size(88, 14), style=0)

        self.tcYingShou = wx.TextCtrl(id=wxID_FRAMESOTCYINGSHOU,
              name=u'tcYingShou', parent=self, pos=wx.Point(160, 440),
              size=wx.Size(80, 22), style=0, value=u'0.0')
        self.tcYingShou.SetEditable(False)
        self.tcYingShou.Enable(False)

        self.staticText_shishou = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_SHISHOU,
              label=u'\u5b9e\u6536\u91d1\u989d\uff1a',
              name=u'staticText_shishou', parent=self, pos=wx.Point(272, 440),
              size=wx.Size(88, 16), style=0)

        self.tcShiShou = wx.TextCtrl(id=wxID_FRAMESOTCSHISHOU,
              name=u'tcShiShou', parent=self, pos=wx.Point(368, 440),
              size=wx.Size(84, 22), style=0, value=u'0.0')
        self.tcShiShou.SetEditable(False)
        self.tcShiShou.Enable(False)

        self.staticText_YouHui = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_YOUHUI,
              label=u'\u4f18\u60e0\u91d1\u989d\uff1a',
              name=u'staticText_YouHui', parent=self, pos=wx.Point(456, 440),
              size=wx.Size(88, 14), style=0)

        self.tcYouHui = wx.TextCtrl(id=wxID_FRAMESOTCYOUHUI, name=u'tcYouHui',
              parent=self, pos=wx.Point(544, 440), size=wx.Size(88, 22),
              style=0, value=u'0.0')
        self.tcYouHui.SetEditable(True)
        self.tcYouHui.Enable(True)

        self.staticText_staff = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_STAFF,
              label=u'\u7ecf\u624b\u4eba\uff1a', name=u'staticText_staff',
              parent=self, pos=wx.Point(72, 480), size=wx.Size(72, 14),
              style=0)

        self.comboBox_staff = wx.ComboBox(choices=[],
              id=wxID_FRAMESOCOMBOBOX_STAFF, name=u'comboBox_staff',
              parent=self, pos=wx.Point(160, 480), size=wx.Size(146, 24),
              style=0, value=u'')
        self.comboBox_staff.SetLabel(u'')

        self.staticText_memo = wx.StaticText(id=wxID_FRAMESOSTATICTEXT_MEMO,
              label=u'\u5907\u6ce8\uff1a', name=u'staticText_memo', parent=self,
              pos=wx.Point(72, 520), size=wx.Size(72, 14), style=0)

        self.tcMemo = wx.TextCtrl(id=wxID_FRAMESOTCMEMO, name=u'tcMemo',
              parent=self, pos=wx.Point(160, 520), size=wx.Size(264, 72),
              style=wx.TE_MULTILINE, value=u'')

        self.gridSOProList = wx.grid.Grid(id=wxID_FRAMESOGRIDSOPROLIST,
              name=u'gridSOProList', parent=self, pos=wx.Point(64, 208),
              size=wx.Size(552, 224), style=wx.SUNKEN_BORDER)
        self.gridSOProList.SetHelpText(u'')
        self.gridSOProList.SetLabel(u'gridSOProList')
        self.gridSOProList.SetToolTipString(u'gridSOProList')
        self.gridSOProList.SetWindowVariant(wx.WINDOW_VARIANT_LARGE)
        self.gridSOProList.SetColLabelSize(32)
        self.gridSOProList.SetRowLabelSize(20)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_CELL_CHANGE,
              self.OnGridSOProListGridCellChange)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_SELECT_CELL,
              self.OnGridSOProListGridSelectCell)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK,
              self.OnGridSOProListGridCellRightClick)

        self.staticBox_history = wx.StaticBox(id=wxID_FRAMESOSTATICBOX_HISTORY,
              label=u'\u6d88\u8d39\u8bb0\u5f55', name=u'staticBox_history',
              parent=self, pos=wx.Point(736, 48), size=wx.Size(448, 512),
              style=0)

        self.TSOID = wx.StaticText(id=wxID_FRAMESOTSOID,
              label=u'XS-2014-03-07-0001', name=u'TSOID', parent=self,
              pos=wx.Point(472, 48), size=wx.Size(162, 16), style=0)
        self.TSOID.SetForegroundColour(wx.Colour(255, 0, 0))

        self.btnHistory = wx.Button(id=wxID_FRAMESOBTNHISTORY,
              label=u'\u5f80\u6765\u5355\u636e', name=u'btnHistory',
              parent=self, pos=wx.Point(760, 80), size=wx.Size(88, 26),
              style=0)
        self.btnHistory.Bind(wx.EVT_BUTTON, self.OnBtnHistoryButton,
              id=wxID_FRAMESOBTNHISTORY)

        self.btnSave = wx.Button(id=wxID_FRAMESOBTNSAVE,
              label=u'\u4fdd\u5b58\u8ba2\u5355', name=u'btnSave', parent=self,
              pos=wx.Point(496, 480), size=wx.Size(93, 26), style=0)
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnBtnSaveButton,
              id=wxID_FRAMESOBTNSAVE)

        self.btnCancel = wx.Button(id=wxID_FRAMESOBTNCANCEL,
              label=u'\u9000\u51fa', name=u'btnCancel', parent=self,
              pos=wx.Point(496, 560), size=wx.Size(93, 26), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_FRAMESOBTNCANCEL)

        self.btnShowCustomer = wx.Button(id=wxID_FRAMESOBTNSHOWCUSTOMER,
              label=u'+', name=u'btnShowCustomer', parent=self,
              pos=wx.Point(328, 88), size=wx.Size(32, 26), style=0)
        self.btnShowCustomer.Bind(wx.EVT_BUTTON, self.OnBtnShowCustomerButton,
              id=wxID_FRAMESOBTNSHOWCUSTOMER)

        self.TCCustomer = wx.TextCtrl(id=wxID_FRAMESOTCCUSTOMER,
              name=u'TCCustomer', parent=self, pos=wx.Point(136, 88),
              size=wx.Size(184, 26), style=0, value=u'')
        self.TCCustomer.SetToolTipString(u'TCCustomer')
        self.TCCustomer.Bind(wx.EVT_TEXT, self.OnTCCustomerText,
              id=wxID_FRAMESOTCCUSTOMER)
        self.TCCustomer.Bind(wx.EVT_KILL_FOCUS, self.OnTCCustomerKillFocus)

        self.staticText1 = wx.StaticText(id=wxID_FRAMESOSTATICTEXT1,
              label=u'\u5546\u54c1\u9500\u552e', name='staticText1',
              parent=self, pos=wx.Point(240, 32), size=wx.Size(84, 20),
              style=0)
        self.staticText1.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, u'\u6977\u4f53_GB2312'))

        self.staticBox1 = wx.StaticBox(id=wxID_FRAMESOSTATICBOX1, label=u'',
              name='staticBox1', parent=self, pos=wx.Point(64, 72),
              size=wx.Size(552, 96), style=0)
        self.staticBox1.SetBackgroundColour(wx.Colour(200, 208, 253))

        self.staticText2 = wx.StaticText(id=wxID_FRAMESOSTATICTEXT2,
              label=u'\u5e94\u6536\u91d1\u989d\uff1a', name='staticText2',
              parent=self, pos=wx.Point(760, 120), size=wx.Size(85, 16),
              style=0)

        self.staticText3 = wx.StaticText(id=wxID_FRAMESOSTATICTEXT3,
              label=u'\u5df2\u6536\u91d1\u989d\uff1a', name='staticText3',
              parent=self, pos=wx.Point(760, 144), size=wx.Size(85, 16),
              style=0)

        self.staticText4 = wx.StaticText(id=wxID_FRAMESOSTATICTEXT4,
              label=u'\u672a\u6536\u91d1\u989d\uff1a', name='staticText4',
              parent=self, pos=wx.Point(760, 168), size=wx.Size(85, 16),
              style=0)

        self.TCTotal = wx.TextCtrl(id=wxID_FRAMESOTCTOTAL, name=u'TCTotal',
              parent=self, pos=wx.Point(848, 112), size=wx.Size(88, 24),
              style=0, value=u'0.0')
        self.TCTotal.SetEditable(False)
        self.TCTotal.SetInsertionPoint(0)
        self.TCTotal.Enable(True)

        self.TCPaid = wx.TextCtrl(id=wxID_FRAMESOTCPAID, name=u'TCPaid',
              parent=self, pos=wx.Point(848, 136), size=wx.Size(88, 24),
              style=0, value=u'0.0')
        self.TCPaid.SetEditable(False)
        self.TCPaid.Enable(True)

        self.TCUnpaid = wx.TextCtrl(id=wxID_FRAMESOTCUNPAID, name=u'TCUnpaid',
              parent=self, pos=wx.Point(848, 160), size=wx.Size(88, 24),
              style=wx.TE_READONLY, value=u'0.0')
        self.TCUnpaid.SetForegroundColour(wx.Colour(255, 0, 0))
        self.TCUnpaid.SetEditable(False)
        self.TCUnpaid.Enable(True)
        self.TCUnpaid.SetBackgroundColour(wx.Colour(255, 255, 255))

        self.btnPrint = wx.Button(id=wxID_FRAMESOBTNPRINT,
              label=u'\u6253\u5370\u5355\u636e', name=u'btnPrint', parent=self,
              pos=wx.Point(496, 520), size=wx.Size(93, 26), style=0)
        self.btnPrint.Bind(wx.EVT_BUTTON, self.OnBtnPrintButton,
              id=wxID_FRAMESOBTNPRINT)

        self.btnPayment = wx.Button(id=wxID_FRAMESOBTNPAYMENT,
              label=u'\u6536\u6b3e', name=u'btnPayment', parent=self,
              pos=wx.Point(392, 480), size=wx.Size(93, 26), style=0)
        self.btnPayment.SetAutoLayout(False)
        self.btnPayment.Bind(wx.EVT_BUTTON, self.OnBtnPaymentButton,
              id=wxID_FRAMESOBTNPAYMENT)

        self.btnAddPro = wx.Button(id=wxID_FRAMESOBTNADDPRO,
              label=u'\u8001\u5546\u54c1\u6dfb\u52a0', name=u'btnAddPro',
              parent=self, pos=wx.Point(64, 176), size=wx.Size(93, 26),
              style=0)
        self.btnAddPro.Bind(wx.EVT_BUTTON, self.OnBtnAddProButton,
              id=wxID_FRAMESOBTNADDPRO)

        self.btnNewPro = wx.Button(id=wxID_FRAMESOBTNNEWPRO,
              label=u'\u65b0\u5546\u54c1\u6dfb\u52a0', name=u'btnNewPro',
              parent=self, pos=wx.Point(176, 176), size=wx.Size(93, 26),
              style=0)
        self.btnNewPro.Bind(wx.EVT_BUTTON, self.OnBtnNewProButton,
              id=wxID_FRAMESOBTNNEWPRO)

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        self.SetSize(Cfg.getDlgAreaSize())
        self.Move(Cfg.getDlgAreaPos())
        
        self.customer = None
        self.fPay = None
        
        #日期
        #import datetime
        #today = datetime.date.today()
        #print today
        #print wx.DateTime.Today().Format('%Y-%m-%d')
        #print wxDateTime::Today()
        #print self.datePickerCtrl1.GetValue()
        #print self.datePickerCtrl1.GetValue().Format('%Y-%m-%d')
        self.dateSO.SetValue(wx.DateTime.Today())
        
        #订单号
        self.refreshSOID()
        
        #订单明细网格
        titles = [(u'编号', 0),
                    (u'产品', 160), 
                    (u'单位', 50), 
                    (u'数量', 70), 
                    (u'单价',70), 
                    (u'小计',100)]
        [self.COL_PROID , self.COL_PRONAME, self.COL_UNIT, self.COL_CNT,
        self.COL_PRICE, self.COL_TOTAL] = [i for i in range(6)]
         
        self.gridSOProList.CreateGrid(0, len(titles))
        for i in range(len(titles)):
            self.gridSOProList.SetColLabelValue(i, titles[i][0])
            self.gridSOProList.SetColSize(i, titles[i][1])
        self.gridSOProList.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        

        #添加右键菜单
        self.orderMenu = wx.Menu()
        self.menuList = [u'添加已有商品', u'添加新商品', u'添加新行', u'删除选中行']
        [self.MENUADDOLD, self.MENUADDNEW, self.MENUINSERTROW, self.MENUDELROW] = \
            [i for i in range(len(self.menuList))]
        for menuItem in self.menuList:
            item = self.orderMenu.Append(-1, menuItem)
            self.Bind(wx.EVT_MENU, self.OnPopupItemSelected, item)
        #无法响应
        #self.gridSOProList.GetGridWindow().Bind(wx.EVT_CONTEXT_MENU, self.OnProListPopup)
        self.gridSOProList.GetGridWindow().Bind(wx.EVT_RIGHT_UP, self.OnGridSOProListRightUp)

        #客户名称
##        for obj in CDataCustomer.m_dataList:            
##            self.comboBox_partner.Append(obj.m_fieldVals[CDataCustomer.getFieldNo(u'name')])
    
        #产品历史
##        self.listCtrl_historyPro = wx.ListCtrl(id=wxID_FRAMESOLISTCTRL_HISTORYPRO,
##              name=u'listCtrl_historyPro', parent=self, pos=wx.Point(760, 200),
##              size=wx.Size(400, 344),
##              style=wx.LC_REPORT|wx.LC_HRULES|wx.LC_VRULES)
##        self.listCtrl_historyPro.SetBackgroundColour(wx.Colour(164, 242, 189))
##        self.listCtrl_historyPro.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL,
##              wx.NORMAL, False, u'Times New Roman'))
##        self.listCtrl_historyPro.Bind(wx.EVT_LEFT_DCLICK,
##              self.OnListCtrl_historyProLeftDclick)
##        cols = [u'单号', u'编号', u'名称', u'规格', u'单位' ,u'最近售价',u'销售总数量',u'销售总金额']
##        #colWidths = [0, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE]
##        #colWidths = [0, wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE_USEHEADER,
##        #                wx.LIST_AUTOSIZE_USEHEADER, wx.LIST_AUTOSIZE_USEHEADER]
##        colFormats = [wx.LIST_FORMAT_LEFT,wx.LIST_FORMAT_LEFT,wx.LIST_FORMAT_LEFT,wx.LIST_FORMAT_LEFT,
##                        wx.LIST_FORMAT_LEFT, wx.LIST_FORMAT_RIGHT, wx.LIST_FORMAT_RIGHT, wx.LIST_FORMAT_RIGHT]
##        colWidths = [0,0,125,125,50,80,0,0]
##        for i in range(len(cols)):
##            self.listCtrl_historyPro.InsertColumn(i, cols[i], colFormats[i], colWidths[i])
##            #self.listCtrl_historyPro.SetColumnWidth(i, colWidths[i])
    
        self.myInit()
        
    def myInit(self):
        
        # 令父窗口随子窗口一同出现
        import kit
        kit.conShow(self)
        
        #self.custWin = PopupTWinCustomer(self)
        #posBtn = self.btnShowCustomer.ClientToScreen((0,0))
        #posPrt = self.ClientToScreen((0,0))
        #sz =  self.btnShowCustomer.GetSize()
        #self.custWin.Position((posPrt.x, posBtn.y + sz.GetHeight()), (0, 0)) 
        
        self.custWin = DlgCustomerChoice.create(self)
        
        self.bSaved = False
        
        self.STATE_NEW = 0
        self.STATE_MODIFY = 1
        self.curState = self.STATE_NEW #default state
        self.preSaleId = ''

        #经手人
        self.cbHandler = MyComboBoxDecorator(self.comboBox_staff, CDataStaff, CDataStaff.COL_NAME)
        self.cbHandler.refresh()
        self.cbHandler.SetValue(Cfg.getCurUser().getValue(CDataStaff.COL_NAME))
        
        self.lcHistory = MyListCtrlCustProRecent(self)
        self.lcHistory.SetSize(wx.Size(400, 360))
        self.lcHistory.Move(wx.Point(760, 200))
        self.lcHistory.Bind(wx.EVT_LEFT_DCLICK, self.OnLcHistoryProLeftDclick)

##    __instance = None
##    def __new__(cls, *args, **kwd):
##        if cls.__instance is None:
##            for i in range(len(cls.__bases__)):
##                cls.__instance = cls.__bases__[i].__new__(cls, *args, **kwd)
##            return cls.__instance
##        else:
##            return None 
##        
##    def __del__(self):
##        type(self).__instance = None
     
    def showCustWin(self):
        posBtn = self.btnShowCustomer.ClientToScreen((0,0))
        posPrt = self.ClientToScreen((0,0))
        sz =  self.btnShowCustomer.GetSize()
        self.custWin.Move((posPrt.x, posBtn.y + sz.GetHeight()))
        self.custWin.Show() 
        
        
    def OnGridSOProListRightUp(self, event):
##        print 'RightUp'
##        print event.GetPosition()
##        pos = self.ScreenToClient(event.GetPosition())
##        print pos
        self.gridSOProList.GetGridWindow().PopupMenu(self.orderMenu, event.GetPosition())
                 
    def OnProListPopup(self, event):
        print 'popup'
        pos = self.ScreenToClient(event.GetPosition())
        self.PopupMenu(self.orderMenu, event.GetPosition())
        event.Skip()
    
    def setGridData(self, listCtrl):
        '''选择销售商品后，显示到销售订单界面，并更新订单总金额'''
        numRows=self.gridSOProList.GetNumberRows()
        if(numRows > 0):
            self.gridSOProList.DeleteRows(numRows=numRows)
        self.gridSOProList.AppendRows()
        
        for i in range(listCtrl.GetItemCount()):
            id = listCtrl.GetItem(i, 0).GetText()
            name = listCtrl.GetItem(i, 1).GetText()
            unit = listCtrl.GetItem(i, 2).GetText()
            cnt = listCtrl.GetItem(i, 3).GetText()
            price = listCtrl.GetItem(i, 4).GetText()
            total = listCtrl.GetItem(i, 5).GetText()
            
            #item = self.gridSOProList.GetNumberRows() - 1
            item = i
            self.gridSOProList.SetCellValue(item, 0, id)
            self.gridSOProList.SetCellValue(item, 1, name)
            self.gridSOProList.SetCellValue(item, 2, unit)
            self.gridSOProList.SetCellValue(item, 3, cnt)
            self.gridSOProList.SetCellValue(item, 4, price)
            self.gridSOProList.SetCellValue(item, 5, total)
            
            self.gridSOProList.AppendRows()

        self.refreshAmount()
    
    def sendGridToList(self, list, grid, rows, cols):
        '''把grid的数据复制到listctrl中（添加到尾部）'''
        #for i in range(grid.GetNumberRows()-1):
            #for i in range(grid.GetNumberCol()):
                
        for i in range(rows):
            row = list.InsertStringItem(sys.maxint, '')
         
            for j in range(cols):
                list.SetStringItem(row, j, grid.GetCellValue(i,j))
                
    def sendListToGrid(self, grid, list, rows, cols):
        '''把listctrl的数据复制到grid中，假定grid空白？？'''
        pass
        
    
    
    def getProOnSale(self):
        '''获取待售商品信息
            目的是把grid中的商品信息发送到添加商品的列表中去
            return - [[proId, proName, unit, cnt, price, total],]
        '''
        proOnsale = []
        
        for i in range(self.gridSOProList.GetNumberRows()):
            row = []

            row.append(self.gridSOProList.GetCellValue(i, self.COL_PROID))
            row.append(self.gridSOProList.GetCellValue(i, self.COL_PRONAME))
            row.append(self.gridSOProList.GetCellValue(i, self.COL_UNIT))
            row.append(self.gridSOProList.GetCellValue(i, self.COL_CNT))
            row.append(self.gridSOProList.GetCellValue(i, self.COL_PRICE))
            row.append(self.gridSOProList.GetCellValue(i, self.COL_TOTAL))

            proOnsale.append(row)
            
        return proOnsale
                    
    def refreshAmount(self):
        amount = 0
        for i in range(self.gridSOProList.GetNumberRows()):
            amount += float(self.gridSOProList.GetCellValue(i, 5))
 
        self.tcYingShou.SetValue(str(amount))
    
    def getDlgPro(self):
        '''该函数存在的原因是选择商品页面不是以dialog形式存在的，而是以main->proInfo
            形式存在的frame
            目前考虑的是如果有多个产品列表，会有数据冗余(实际上没多少数据)
            因此，把当前saleorder设为main.fSO，这样fPro中选择完商品后会
            设置到该saleorder
        '''
        self.GetParent().fSO = self
        return  self.GetParent().fPro

    def getGridData(self):
        proOnsale = []
        for row in range(self.gridSOProList.GetNumberRows()):
            dataRow = []
            for col in range(self.gridSOProList.GetNumberCols()):
                dataRow.append(self.gridSOProList.GetCellValue(row, col))

            proOnsale.append(dataRow)
            
        return proOnsale
    
##    def appendSaleList(self, data):
##        '''添加商品到代售列表
##            DATA - ((proId, proName, unit, cnt, price, total),(...))'''
##        for i in range(len(data)):
##            item = self.gridSOProList.GetNumberRows() - 1
##            self.gridSOProList.SetCellValue(item, 0, str(data[i][0]))
##            #在win7-64bit上出现编码问题
##            #self.gridSOProList.SetCellValue(item, 1, str(data[i][1]))
##            #self.gridSOProList.SetCellValue(item, 2, str(data[i][2]))
##            self.gridSOProList.SetCellValue(item, 1, data[i][1])
##            self.gridSOProList.SetCellValue(item, 2, data[i][2])
##            self.gridSOProList.SetCellValue(item, 3, str(data[i][3]))
##            self.gridSOProList.SetCellValue(item, 4, str(data[i][4]))
##            self.gridSOProList.SetCellValue(item, 5, str(data[i][5]))
##            
##            self.gridSOProList.AppendRows()
##            
##        self.refreshAmount()
        
    def appendProDetail(self, dataList):
        '''dataList - [[id,name,unit,cnt,price,total],[...]]'''
        print dataList
        grid = self.gridSOProList
        for i in range(len(dataList)):
            row = grid.GetNumberRows()
            grid.AppendRows()
            for col in range(len(dataList[0])):
                grid.SetCellValue(row, col, kit.myStr(dataList[i][col]))
        
        # 添加新数据后，自动重新计算总金额                    
        self.refreshAmount()
        
    def OnPopupItemSelected(self, event):
        '''代售产品网格右键菜单处理：添加、删除'''
        item = self.orderMenu.FindItemById(event.GetId())
        print item.GetText()
        if (item.GetText() == self.menuList[self.MENUADDOLD]):
            #添加商品
            #dlgPro = self.getDlgPro()
            #dlgPro.setShowState(dlgPro.STATE_XS)
            #dlgPro.Show()
            #dlgPro.Raise()
            #self.sendGridToList(dlgPro.listCtrl_proSel,
            #                    self.gridSOProList,
            #                    self.gridSOProList.GetNumberRows() - 1,
            #                    self.gridSOProList.GetNumberCols())
            
            #dlg = DlgSelectPro.create(self)
            #dlg.setViewState(DlgSelectPro.TypeSale, self.customer)
            dlg = DlgSelectPro.create(self.GetParent(), DlgSelectPro.TypeSale, self.customer)
            
            dlg.appendProDetail(self.getGridData())                    
            if(dlg.ShowModal() == wx.ID_OK):
                numRows=self.gridSOProList.GetNumberRows()
                if(numRows > 0):
                    self.gridSOProList.DeleteRows(numRows=numRows)
                # ClearGrid()只会清除数据，不会删除空行
                #self.gridSOProList.ClearGrid()
                self.appendProDetail(dlg.getProSaleList())
            
            
        elif (item.GetText() == self.menuList[self.MENUADDNEW]):
            #添加并选择新商品
            dlg = DlgEditPro.create(self)
            if (dlg.ShowModal() == wx.ID_OK):
                pass
            
        elif (item.GetText() == self.menuList[self.MENUINSERTROW]):
            #add new line
            pass
        elif (item.GetText() == self.menuList[self.MENUDELROW]):
            rows = self.gridSOProList.GetSelectedRows()
            print rows
            for index in rows:
                self.gridSOProList.DeleteRows(index)
            
        else:
            print 'UnKnown CMD %s' %(item.GetText())
        
        self.refreshAmount()
            
    def refreshSOID(self):
        date = self.dateSO.GetValue().Format('%Y%m%d')
        id = CDataSaleOrder.newId(date)
        print date
        self.TSOID.SetLabel(id)
##        self.TSOID.SetLabel('XS-%s-%05d' %(self.dateSO.GetValue().Format('%Y-%m-%d'), 
##                                dbmngr.db_getSONum(self.dateSO.GetValue())))

    def addEventAlert(self, title, content):
        import DlgEventEditor
        dlg = DlgEventEditor.create(self)
        dlg.setData(title, content)
        dlg.ShowModal()
                
    def OnFrameSOClose(self, event):
        #self.Show(False)
        #self.GetParent().Show()
        if not (self.bSaved):
            if (self.curState == self.STATE_MODIFY):
                msg = u'订单没有保存，退出后修改的内容将不会保存，是否继续退出?'
            else:
                msg = u'订单没有保存，退出后将丢失当前数据，是否继续退出?'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_YES):
                self.Destroy()
            return
        
        if (self.curState == self.STATE_MODIFY):
            # 修改模式不进行收款测试，直接退出
            self.Destroy()
                
        paid = float(self.tcShiShou.GetValue())
        if (paid == 0.0 and self.btnPayment.IsEnabled() and self.btnPayment.IsShown()):
            dlg = wx.MessageDialog(self, u'该订单没有收款信息，是否继续退出?',u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_NO):
                return
        
        # event alarm:debt
        amount = float(self.tcYingShou.GetValue())
        discount = float(self.tcYouHui.GetValue())
        debt = amount-paid-discount
        if (debt > 0.0):
            msg = u'该订单欠款%.2f元，是否添加到开机提醒?' %debt
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_YES):
                title = u'【%s】的订单【%s】欠款%.2f元' \
                        %(self.customer.getValue(CDataCustomer.COL_NAME),
                        self.TSOID.GetLabel(),
                        debt)
                self.addEventAlert(title, title)
        self.Destroy()

    def OnDateSODateChanged(self, event):
        if (self.curState == self.STATE_MODIFY):
            msg = u'改变日期会导致单据编号发生变化，原来针对此订单的收款等信息将丢失，'\
                    u'是否继续修改？'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_NO):
                return
            
        self.refreshSOID()    

    def OnBtnShowCustomerButton(self, event):
##        btn = event.GetEventObject()
##        posBtn = btn.ClientToScreen((0,0))
##        posPrt = self.ClientToScreen((0,0))
##        sz =  btn.GetSize()
##        self.custWin.Position((posPrt.x, posBtn.y + sz.GetHeight()), (0, 0))
        #self.custWin.Popup()
        #self.custWin.Show()
        self.showCustWin()


    def setCustomer(self, obj):
        '''选择销售客户，更改客户需要清空当前的数据
            @param
            obj - customer selected 
        '''
        #clear some data input before
        #self.gridSOProList.DeleteRows(numRows=self.gridSOProList.GetNumberRows()-1)
        
        self.customer = obj
        
        custName = obj.getFieldVal(field='name')
        
        title = u'销售订单--%s' %custName
        self.SetTitle(title)
        
        #设置客户名称，采用changevalue()避免产生新事件    
        #self.TCCustomer.SetValue(obj.getFieldVal(field='name'))
        self.TCCustomer.ChangeValue(custName)
        
        #customer id
        id = obj.getFieldVal(field='id')
        
        #设置送货地址
        print 'TODO:delivery info'
        self.dlvyChoices = []
        self.dlvyObjList = CRelCustDlvy.getDlvy(id)
        for dlvyObj in self.dlvyObjList:
            dlvyName = dlvyObj.getFieldVal(index=CDataDelivery.COL_NAME)
            self.dlvyChoices.append(dlvyName)
            self.comboBox_delivery.Append(dlvyName)
        
        #设置消费记录
        total = obj.getSaleAmount() + obj.getInitDebt()
        paid = obj.getPaidAmount()
        self.TCTotal.SetValue(str(total))
        self.TCPaid.SetValue(str(paid))
        self.TCUnpaid.SetValue(str(total - paid))

        #设置曾经购买的产品列表
        self.lcHistory.refresh({'peerId':id})
##        self.listCtrl_historyPro.DeleteAllItems()
##        proList = CDataSaleDetail.getCustomerExpense(id)
##        if (proList is not None):
##            for item in proList:
##                proId,proName,unit,price,saleId,cnt,amount = item
##                
##                proObj = CDataProduct.getData({'id':proId})
##                if (proObj is None):
##                    print '[Error] None id %d' %proId
##                
##                proSpec = proObj.getFieldVal('spec')
##
##                CListCtrlAider.appendItem(self.listCtrl_historyPro,
##                                        (saleId,str(proId),proName,proSpec, unit, str(price),str(cnt),str(amount)))

    def setData(self, saleId):
        '''设置要编辑的订单数据'''
        self.curState = self.STATE_MODIFY
        self.btnPayment.Show(False)
        
        self.preSaleId = saleId
        self.loadSaleOrder(saleId)
        self.loadSaleDetails(saleId)
        
    def loadSaleOrder(self, saleId):
        sql = "id='%s'" %saleId
        objs = CDataSaleOrder.fetch(sql)
        if (len(objs) != 1):
            print 'Error incorrect billId:%s' %saleId
            
        soObj = objs[0]
        self.TSOID.SetLabel(soObj.getFieldVal(index=CDataSaleOrder.COL_ID))
        
        custId = soObj.getFieldVal(index=CDataSaleOrder.COL_PEERID)
        custObj = CDataCustomer.getFirstInstance({CDataCustomer.COL_ID:custId})
        self.setCustomer(custObj)
        
##        dlvyId = soObj.getFieldVal(index=CDataSaleOrder.COL_DLVYID)
##        if (dlvyId is not None):
##            dlvyObj = CDataDelivery.getFirstInstance({CDataDelivery.COL_ID:dlvyId})
##            dlvyName = dlvyObj.getFieldVal(index=CDataDelivery.COL_NAME)
##            self.comboBox_delivery.SetStringSelection(dlvyName)
        self.comboBox_delivery.SetStringSelection(soObj.getValue(CDataSaleOrder.COL_DLVYADDR))
        date = soObj.getFieldVal(index=CDataSaleOrder.COL_BILLDATE)
        print date
        #print str(date)
        #self.dateSO.SetLabel(str(date))
##        date = str(date)
##        day = int(date[-2:])
##        month = int(date[5:7])
##        year = int(date[:4])
##        print '%s %s %s' %(day, month, year)
##        self.dateSO.SetValue(wx.DateTimeFromDMY(day, month -1, year, 0, 0, 0))
        print '%s %s %s' %(date.day, date.month, date.year)
        self.dateSO.SetValue(wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0))

        self.tcYingShou.SetValue(str(soObj.getFieldVal(index=CDataSaleOrder.COL_TOTAL)))
        #COL_PAID,
        #self.tcShiShou.SetValue(str(soObj.getFieldVal(index=CDataSaleOrder.COL_PAID)))
        
        #COL_UNPAID,
      
        self.tcYouHui.SetValue(str(soObj.getFieldVal(index=CDataSaleOrder.COL_DISCOUNT)))
        
        #COL_HANDLERID,
        #COL_RECOREDERID,
        hId = soObj.getFieldVal(index=CDataSaleOrder.COL_HANDLERID)
        hObj = CDataStaff.getFirstInstance({CDataStaff.COL_ID:hId})
        self.cbHandler.SetValue(hObj.getValue(CDataStaff.COL_NAME))
        
        self.tcMemo.SetValue(soObj.getFieldVal(index=CDataSaleOrder.COL_MEMO))
        
    def loadSaleDetails(self, saleId):
        '''把销售产品明细显示到grid'''
        grid = self.gridSOProList
        
        sql = "billId='%s'" %saleId
        objList = CDataSaleDetail.fetch(sql)
            
        for i in range(len(objList)):
            grid.AppendRows()
            grid.SetCellValue(i, self.COL_PROID, 
                        str(objList[i].getFieldVal(index=CDataSaleDetail.COL_PROID)))
            grid.SetCellValue(i, self.COL_PRONAME, 
                        objList[i].getFieldVal(index=CDataSaleDetail.COL_PRONAME))
            grid.SetCellValue(i, self.COL_UNIT, 
                        objList[i].getFieldVal(index=CDataSaleDetail.COL_UNIT))
            grid.SetCellValue(i, self.COL_CNT, 
                        str(objList[i].getFieldVal(index=CDataSaleDetail.COL_NUM)))
            grid.SetCellValue(i, self.COL_PRICE, 
                        str(objList[i].getFieldVal(index=CDataSaleDetail.COL_PRICE)))
            grid.SetCellValue(i, self.COL_TOTAL, 
                        str(objList[i].getFieldVal(index=CDataSaleDetail.COL_TOTAL)))
            
        self.refreshAmount()
        
    def delSaleOrderDetails(self, saleId):
        CDataSaleDetail.delData({CDataSaleDetail.COL_BILLID:saleId})
    
    def delSaleOrder(self, saleId):
        CDataSaleOrder.delData({CDataSaleOrder.COL_ID:saleId})
        
    def delData(self, saleId):
        self.delSaleOrderDetails(saleId)
        self.delSaleOrder(saleId)
            
    def OnLcHistoryProLeftDclick(self, event):
        '''左键双击直接选择曾经购买的商品'''

        proId,proName,unit,price = self.lcHistory.getProSaleInfo()
        
        dlg = DlgProGX(self)
        dlg.setData(proId=proId, unit=unit, price=price)
        
        if (dlg.ShowModal() == wx.ID_OK):

            unit = dlg.unit
            cnt = dlg.cnt
            price = dlg.price
            total = dlg.cnt*dlg.price
            data = []
            data.append([proId, proName, unit, cnt, price, total])
            self.appendProDetail(data)

    [COL_PROID, COL_PRONAME, COL_UNIT, COL_CNT, COL_PRICE, COL_TOTAL] = [i for i in range(6)]
    def OnGridSOProListGridCellChange(self, event):
        '''改变<单价><数量>时，重新计算<小计><应收金额>'''
        print 'OnGridSOProListGridCellChange'
        if (event.GetCol() < 3 or event.GetCol() > 4):
            #cnt\price unchanged
            return
        try:
            row = event.GetRow()
            total = float(self.gridSOProList.GetCellValue(row, self.COL_CNT)) * \
                        float(self.gridSOProList.GetCellValue(row, self.COL_PRICE))
            self.gridSOProList.SetCellValue(row, self.COL_TOTAL, str(total))
            
            self.refreshAmount() 
        except ValueError,e:
            print e
            dlg = wx.MessageDialog(self, u'输入错误：请输入数值',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            self.gridSOProList.SetGridCursor(row, event.GetCol())
            
    def saveSaleOrderToDB(self):
        pass
    
    def saveSaleDetailsToDB(self):
        pass
    
    def checkDlvy(self, dlvyName):
        dlvyId = -1
        for i in range(len(self.dlvyObjList)):
            if dlvyName == self.dlvyObjList[i].getFieldVal(index=CDataDelivery.COL_NAME):
                dlvyId = self.dlvyObjList[i].getFieldVal(index=CDataDelivery.COL_ID)
                break
                
        #如果配送地址是新的，则添加到数据库        
        if dlvyId == -1:
            #添加新的配送方式
            
##            dlvyId = CDataDelivery.newAutoIncrId()
##            print '********newid %d***********' %dlvyId
##            newDlvy = CDataDelivery()
##            newDlvy.setMulFieldVal({CDataDelivery.COL_ID:dlvyId, 
##                                    CDataDelivery.COL_NAME:dlvyName})
##            newDlvy.insertNewData()
            
            dlvyId = CDataDelivery.tryInsert({CDataDelivery.COL_ID:dlvyId, 
                                    CDataDelivery.COL_NAME:dlvyName})
                                    
            #添加新的客户-配送关系
##            newCustDlvy = CRelCustDlvy()
##            newCustDlvy.setMulFieldVal({CRelCustDlvy.COL_CUSTID:self.customer.getFieldVal('id'), 
##                                    CRelCustDlvy.COL_DLVYID:dlvyId})
##            newCustDlvy.insertNewData()
            CRelCustDlvy.quickInsert({CRelCustDlvy.COL_CUSTID:self.customer.getValue(self.customer.COL_ID), 
                                    CRelCustDlvy.COL_DLVYID:dlvyId})
        
    def OnBtnSaveButton(self, event):
        '''保存订单'''
        if (self.customer is None):
            dlg = wx.MessageDialog(self, u'订单未完成：请选择客户',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        if (self.gridSOProList.GetNumberRows() <= 0):
            dlg = wx.MessageDialog(self, u'订单未完成：未选择产品',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
##        paid = float(self.tcShiShou.GetValue())
##        if (paid == 0):
##            dlg = wx.MessageDialog(self, u'客户未付款金额？',u'提示',wx.YES_NO|wx.ICON_QUESTION)
##            if (dlg.ShowModal() == wx.ID_NO):    
##                return
        
        dlg = wx.MessageDialog(self, u'订单保存后将无法修改，请确定是否保存订单?',u'提示',wx.YES_NO|wx.ICON_QUESTION)
        if(dlg.ShowModal() == wx.ID_NO):
            return
        
        #收款
##        if (self.fPay is None):
##            self.fPay = DlgPayment.create(self)
##            
##        try:
##            self.fPay.setCustMode(self.customer, self.tcYingShou.GetValue(), self.TSOID.GetLabel())
##        except wx.PyDeadObjectError:
##            self.fPay = DlgPayment.create(self)
##            self.fPay.setCustMode(self.customer, self.tcYingShou.GetValue(), self.TSOID.GetLabel())
##       
##       
##        if(self.fPay.ShowModal() == wx.ID_CANCEL):
##            return
##            
##        self.tcShiShou.SetValue(str(self.fPay.getMoney()))
            
        #
        if(self.curState == self.STATE_MODIFY and self.preSaleId != ''):
            self.delData(self.preSaleId)
            
        #配送地址
        dlvyName = self.comboBox_delivery.GetValue()
        if (dlvyName != ''):       
            self.checkDlvy(dlvyName)
                           
        #保存订单数据到数据库saleorder\saledetails
        self.saveSaleOrderToDB()
        obj = CDataSaleOrder.factory()
        obj.setFieldVal(self.TSOID.GetLabel(), field='id')
        obj.setFieldVal(self.customer.getFieldVal('id'),field='peerId')
        obj.setFieldVal(dlvyName,field='dlvyAddr')
        obj.setFieldVal(self.dateSO.GetValue().Format('%Y-%m-%d'), field='billDate')
        
        total = float(self.tcYingShou.GetValue())
        paid = float(self.tcShiShou.GetValue())
        discount = float(self.tcYouHui.GetValue())
        unpaid = total - paid - discount
        obj.setFieldVal(total,field='total')
        
        obj.setFieldVal(paid,field='paid')
        obj.setFieldVal(unpaid,field='unpaid')
        obj.setFieldVal(discount,field='discount')
        
        handlerId = self.cbHandler.getSelectObj().getValue(CDataStaff.COL_ID)
        recorderId = Cfg.getCurUser().getValue(CDataStaff.COL_ID) 
        obj.setFieldVal(handlerId,field='handlerId')#TODO
        obj.setFieldVal(recorderId,field='recorderId')#TODO
        
        obj.setFieldVal(self.tcMemo.GetValue(),field='memo')
        obj.insert()
                  
        for i in range(self.gridSOProList.GetNumberRows()):
            item = CDataSaleDetail.factory()
            print 'CDataSaleDetail %d' %i
            item.setFieldVal(obj.getFieldVal('id'), field='billId')
            item.setFieldVal(self.customer.getFieldVal('id'), field='peerId')
            print 'CDataSaleDetail %d' %i
            item.setFieldVal(self.gridSOProList.GetCellValue(i, 0), field='proId')
            print 'CDataSaleDetail %d' %i
            #self.gridSOProList.SetCellValue(item, 2, unit)
            item.setFieldVal(self.gridSOProList.GetCellValue(i, 1), field='proName')
            item.setFieldVal(self.gridSOProList.GetCellValue(i, 2), field='unit')
            
            item.setFieldVal(self.gridSOProList.GetCellValue(i, 4), field='price')
            print 'CDataSaleDetail %d' %i
            item.setFieldVal(self.gridSOProList.GetCellValue(i, 3), field='num')
            print 'CDataSaleDetail %d' %i
            item.setFieldVal(self.gridSOProList.GetCellValue(i, 5), field='total')
            print 'CDataSaleDetail %d' %i
            item.insert()
        
        #self.Close()
        self.TCCustomer.Disable()
        self.comboBox_delivery.Disable()
        self.gridSOProList.Disable()
        self.tcMemo.Disable()
        self.dateSO.Disable()
        self.comboBox_staff.Disable()
        
        self.btnSave.Disable()
    
        self.bSaved = True
    
    def OnBtnSavePrintButton(self, event):
        self.OnBtnSaveButton(event)

    def OnBtnCancelButton(self, event):
        self.Close()

    def OnTCCustomerText(self, event):
        print 'OnTCCustomerText'
        self.TCCustomer.SetFocus()

        str = self.TCCustomer.GetValue()
        self.custWin.setFilter(str)
        #self.custWin.Show()
        if not self.custWin.IsShown():
            print 'first show custwin'
            self.showCustWin()
            print 'TCCustomer.SetFocus'
            #import time
            #time.sleep(1)
            self.TCCustomer.SetFocus()
        
    def OnTCCustomerKillFocus(self, event):
        print 'OnTCCustomerKillFocus'
        print 'active %d' %self.custWin.IsActive()
        print 'focus %s' %self.custWin.FindFocus()
        #以下语句很奇怪，导致自动触发KillFocus
        
        if not self.custWin.IsActive():
            self.custWin.Show(False)

        #self.custWin.Show(False)

    

    def OnBtnPrintButton(self, event):
        if not (self.bSaved):
            dlg = wx.MessageDialog(self, u'请先保存单据，然后再进行打印',u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        MyPrinter.printSaleOrder(self, self.TSOID.GetLabel())

    def OnBtnPaymentButton(self, event):
        if not (self.bSaved):
            dlg = wx.MessageDialog(self, u'请先保存单据，然后再进行收款',u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return
        
        dlg = DlgPayment.create(self)
        saleId = self.TSOID.GetLabel()
        dlg.setData(saleId)
        #dlg.setCustMode(self.customer, self.tcYingShou.GetValue(), self.TSOID.GetLabel())
        if(dlg.ShowModal() == wx.ID_CANCEL):
            return

        self.btnPayment.Disable()
        self.tcShiShou.SetValue(str(dlg.getMoney()))

    def OnBtnHistoryButton(self, event):
        if (self.customer is None):
            return
        
        import DlgFundCustomer
        dlg = DlgFundCustomer.create(self)
        dlg.Show()
        dlg.setCustomer(self.customer)
        dlg.refresh()


    def OnGridSOProListGridSelectCell(self, event):
        #print event.GetRow()
        self.gridSOProList.SelectRow(event.GetRow())
        event.Skip()

    def OnGridSOProListGridCellRightClick(self, event):
        #print event.GetRow()
        self.gridSOProList.SelectRow(event.GetRow())
        event.Skip()

    def addOldPro(self):
        import DlgSelectPro
        dlg = DlgSelectPro.create(self.GetParent(), DlgSelectPro.TypeSale, self.customer)
            
        dlg.appendProDetail(self.getGridData())                    
        if(dlg.ShowModal() == wx.ID_OK):
            numRows=self.gridSOProList.GetNumberRows()
            if(numRows > 0):
                self.gridSOProList.DeleteRows(numRows=numRows)
            # ClearGrid()只会清除数据，不会删除空行
            #self.gridSOProList.ClearGrid()
            self.appendProDetail(dlg.getProSaleList())
    
    def addNewPro(self):
        import DlgEditPro
        dlg = DlgEditPro.create(self)
        if (dlg.ShowModal() == wx.ID_OK):
            proObj = dlg.getProObj()
            
            proId = proObj.getValue(proObj.COL_ID)
            proName = proObj.getValue(proObj.COL_NAME)
            unit = proObj.getValue(proObj.COL_UNIT1)
            cnt = 0.0
            price = proObj.getValue(proObj.COL_DEFSALE1)
            total = kit.myFloat(cnt) * kit.myFloat(price)
            self.appendProDetail([[proId, proName, unit, cnt, price,total]])
        
            self.gridSOProList.SetFocus()
            row = self.gridSOProList.GetNumberRows() - 1
            self.gridSOProList.SetGridCursor(row, self.COL_CNT)
        
                        
    def OnBtnAddProButton(self, event):
        self.addOldPro()
        event.Skip()

    def OnBtnNewProButton(self, event):
        self.addNewPro()
        event.Skip()
        

